/*---------------------------------------------------------------------
 * File name: modbus.cpp
 *
 * Copyright (c) <2020-2022>, <ChenLong>
 *
 * All rights reserved.
 *
 * Author: ChenLong
 * Email: worldlong@foxmail.com
 *--------------------------------------------------------------------*/
#pragma once
/*
 */
#include "string.h"
#include "modbus.h"
/*
*/
static const uint16_t crc_table[256] = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
/*
*/
ModbusBase::ModbusBase(uint8_t my_id0) :
    pdu{0},
    data_length(0),
    my_id(my_id0),
    packet_mask(0)
{
  pdu.data = buffer0;
  //for crc test
  pdu.crc = calc_crc((uint8_t*)crc_table, 10);
}
/*
*/
int ModbusBase::packet(uint8_t **ptr)
{
  int index = 0;
  buffer0[index++] = pdu.id;
  buffer0[index++] = pdu.cmd;
  if(packet_mask & 0x01) {
    buffer0[index++] = pdu.address >> 8;
    buffer0[index++] = pdu.address;
  }
  if(packet_mask & 0x02) {
    buffer0[index++] = pdu.number >> 8;
    buffer0[index++] = pdu.number;
  }
  if(packet_mask & 0x04) {
    buffer0[index++] = pdu.bytes;
  }
  
  index += data_length;
  buffer0[index++] = pdu.crc >> 8;
  buffer0[index++] = pdu.crc;
  
  *ptr = buffer0;
  return index;
}
/*
*/
void ModbusBase::build_start(uint8_t id, uint8_t cmd, uint16_t address, uint16_t number, uint8_t bytes)
{
  pdu.id = id;
  pdu.cmd = cmd;
  pdu.address = address;
  pdu.number = number;
  pdu.bytes = bytes;
  pdu.data = buffer0 + 7;
  data_length = 0;
  packet_mask = 0x07;
}
/*
*/
void ModbusBase::build_start(uint8_t id, uint8_t cmd, uint16_t address, uint16_t number)
{
  build_start(id, cmd, address, number, number*2);
  pdu.data = buffer0 + 6;
  packet_mask = 0x03;
}
/*
*/
void ModbusBase::build_start(uint8_t id, uint8_t cmd, uint16_t address)
{
  build_start(id, cmd, address, 1, 2);
  pdu.data = buffer0 + 4;
  packet_mask = 0x01;
}
/*
*/
void ModbusBase::build_start(uint8_t id, uint8_t cmd, uint8_t bytes)
{
  build_start(id, cmd, pdu.address, pdu.number, bytes);
  pdu.data = buffer0 + 3;
  packet_mask = 0x04;
}
/*
*/
void ModbusBase::build_start(uint8_t id, uint8_t cmd)
{
  pdu.id = id;
  pdu.cmd = cmd;
  data_length = 0;
  packet_mask = 0;
}
/*
 */
void ModbusBase::build_end()
{
  //crc calc
  uint16_t crc = 0xffff;
  crc = byte_crc(crc, pdu.id);
  crc = byte_crc(crc, pdu.cmd);
  if ((packet_mask & 0x01) != 0)
  {
      crc = byte_crc(crc, (uint8_t)(pdu.address >> 8));
      crc = byte_crc(crc, (uint8_t)(pdu.address));
  }
  if ((packet_mask & 0x02) != 0)
  {
      crc = byte_crc(crc, (uint8_t)(pdu.number >> 8));
      crc = byte_crc(crc, (uint8_t)(pdu.number));
  }
  if ((packet_mask & 0x04) != 0)
  {
      crc = byte_crc(crc, (uint8_t)(pdu.bytes));
  }
  crc = calc_crc(crc, pdu.data, data_length);
  //exchange msb and lsb
  pdu.crc = (crc >> 8) | (crc << 8);
}
/*
*/
uint16_t ModbusBase::byte_crc(uint16_t crc, uint8_t data)
{
  int index = ((crc & 0xff) ^ (data & 0xff));
  return ((crc >> 8) & 0xff) ^ crc_table[index];
}
/*
*/
uint16_t ModbusBase::calc_crc(uint16_t crc, uint8_t *buffer, uint16_t len)
{
  int index;
    for (int i = 0; i < len; i++) {
        index = ((crc & 0xff) ^ (buffer[i] & 0xff));
        crc = ((crc >> 8) & 0xff) ^ crc_table[index];
    }

    return crc;
}
/*
*/
uint16_t ModbusBase::calc_crc(uint8_t *buffer, uint16_t length) 
{
  return calc_crc(0xffff, buffer, length);
}
/*
*/
uint16_t ModbusBase::calc_crc_ex(uint8_t *buffer, uint16_t length) 
{
  uint16_t crc = calc_crc(0xffff, buffer, length);
  return (crc >> 8) | (crc << 8);
}
/*
 */
void ModbusBase::insert_u8(uint8_t data)
{
  pdu.data[data_length++] = data;
}
/*
 Big-Endian
 */
void ModbusBase::insert_u16(uint16_t data)
{
  pdu.data[data_length++] = (uint8_t)(data >> 8);
  pdu.data[data_length++] = (uint8_t)data;
}
/*
Big-Endian
 */
void ModbusBase::insert_u24(uint32_t data)
{
  pdu.data[data_length++] = (uint8_t)(data >> 16);
  pdu.data[data_length++] = (uint8_t)(data >> 8);
  pdu.data[data_length++] = (uint8_t)data;
}
/*
Big-Endian
 */
void ModbusBase::insert_u32(uint32_t data)
{
  pdu.data[data_length++] = (uint8_t)(data >> 24);
  pdu.data[data_length++] = (uint8_t)(data >> 16);
  pdu.data[data_length++] = (uint8_t)(data >> 8);
  pdu.data[data_length++] = (uint8_t)data; 
}
/*
Big-Endian
 */
void ModbusBase::insert_f32(float data)
{
  uint32_t tmp;
  tmp = *((uint32_t*)(&data));
  insert_u32(tmp);
}
/*
 */
void ModbusBase::insert_bytes(uint8_t *buffer, int number)
{
  memcpy(pdu.data + data_length, buffer, number);
  data_length += number;
}
/*
 */
void ModbusBase::insert_string(char *str)
{
  strcpy((char*)(&pdu.data[data_length]), str);
  data_length += strlen(str) + 1;
}

/*
Big-Endian
 */
uint8_t ModbusBase::extract_u8(int index)
{
  return pdu.data[index];
}

/*
Big-Endian
 */
uint16_t ModbusBase::extract_u16(int index)
{
  return (uint16_t)((pdu.data[index] << 8) + pdu.data[index + 1]);
}

/*
Big-Endian
 */
uint32_t ModbusBase::extract_u24(int index)
{
  return (uint32_t)((pdu.data[index] << 16) + (pdu.data[index + 1] << 8) + pdu.data[index + 2]);
}

/*
Big-Endian
 */
uint32_t ModbusBase::extract_u32(int index)
{
  return (uint32_t)((pdu.data[index] << 24) + (pdu.data[index + 1] << 16) + (pdu.data[index + 2] << 8) + pdu.data[index + 3]);
}

/*
Big-Endian
 */
float ModbusBase::extract_f32(int index)
{
  uint32_t tmp = extract_u32(index);
  return *(float*)(&tmp);
}

/*
Big-Endian
 */
uint32_t ModbusBase::extract_bytes(uint8_t *buffer, int number, int index)
{
  memcpy(buffer, &pdu.data[index], number);
  return number;
}

/*
Big-Endian
 */
uint32_t ModbusBase::extract_string(char *str, int index)
{
  strcpy(str, (char const*)(&pdu.data[index]));
  return strlen(str) + 1;
}


/*
*/
int ModbusBase::packet_read(uint8_t **ptr, uint8_t slave_id, uint8_t cmd, uint16_t address, uint16_t number)
{
  build_start(slave_id, cmd, address, number);
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_write_single(uint8_t **ptr, uint8_t slave_id, uint8_t cmd, uint16_t address, uint16_t data)
{
  build_start(slave_id, cmd, address);
  insert_u16(data);
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_write_multiply(uint8_t **ptr, uint8_t slave_id, uint8_t cmd, uint16_t address, uint16_t number, uint16_t *data)
{
  build_start(slave_id, cmd, address, number, (uint8_t)(number * 2));
  for(int i=0; i<number; i++) {
    insert_u16(data[i]);
  }
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_write_read_test(uint8_t **ptr, uint8_t slave_id, uint8_t number, uint8_t *data)
{
  build_start(slave_id, MODBUS_CMD_WRT, number);
  insert_bytes(data, number);
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_read_ack(uint8_t **ptr, uint16_t *data)
{
  build_start(pdu.id, pdu.cmd, (uint8_t)(pdu.number*2));
  for(int i=0; i<pdu.number; i++) {
    insert_u16(data[i]);
  }
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_write_ack(uint8_t **ptr)
{
  build_start(pdu.id, pdu.cmd, pdu.address, pdu.number);
  build_end();
  return packet(ptr);
}
/*
*/
int ModbusBase::packet_error_ack(uint8_t **ptr)
{
  build_start(pdu.id, MODBUS_ACK_ERR);
  build_end();
  return packet(ptr);
}
/*
*/
mdet_t ModbusBase::master_parse(uint8_t *buffer, int len, bool crc_enable)
{
  if (len < 2){
    return MDET_BADFRAME;
  }
  
  if(crc_enable) {
    //crc check
    pdu.crc = (uint16_t)(((uint16_t)buffer[len - 1] << 8) + (uint16_t)buffer[len - 2]);
    if (pdu.crc != calc_crc(buffer, len - 2)) {
        return MDET_BADCRC;
    }
  }
  
  if(pdu.id != buffer[0]) {
    return MDET_BADACK;
  }
  
  if(MODBUS_ACK_ERR == buffer[1]) {  //ACK error 
    pdu.cmd = MODBUS_ACK_ERR;
    return MDET_OK;
  }
  
  if(pdu.cmd != buffer[1]) {
    return MDET_BADACK;
  }
  
  int index = 2;
  if(pdu.cmd == MODBUS_CMD_WKB || pdu.cmd == MODBUS_CMD_WKR) {
    uint16_t address = buffer[index++] << 8;
    address += buffer[index++];
    if(pdu.address != address) {
      return MDET_BADACK;
    }
    pdu.bytes = 2;
  } else if(pdu.cmd == MODBUS_CMD_WKBS || pdu.cmd == MODBUS_CMD_WKRS) {
    uint16_t address = buffer[index++] << 8;
    address += buffer[index++];
    uint16_t number = buffer[index++] << 8;
    number += buffer[index++];
    if(pdu.address != address || pdu.number != number) {
      return MDET_BADACK;
    }
    pdu.bytes = 0;
  } else {  //read or test
    pdu.bytes = buffer[index++];
  }
  //copy data
  pdu.data = buffer + index;
  return MDET_OK;
} 
/*
*/
mdet_t ModbusBase::slave_parse(uint8_t *buffer, int len, bool crc_enable)
{
  if (len < 2){
    return MDET_BADFRAME;
  }
  
  if(buffer[0] != my_id) {
    return MDET_BADID;
  }
  
  if(crc_enable) {
    //crc check
    pdu.crc = (uint16_t)(((uint16_t)buffer[len - 1] << 8) + (uint16_t)buffer[len - 2]);
    if (pdu.crc != calc_crc(buffer, len - 2)) {
        return MDET_BADCRC;
    }
  }
  
  pdu.id = buffer[0];
  pdu.cmd = buffer[1];
  
  int index = 2;
  if(pdu.cmd == MODBUS_CMD_WKB || pdu.cmd == MODBUS_CMD_WKR) {
    pdu.address = buffer[index++] << 8;
    pdu.address += buffer[index++];
    pdu.number = 1;
    pdu.bytes = 2;
  } else if(pdu.cmd == MODBUS_CMD_WKBS || pdu.cmd == MODBUS_CMD_WKRS) {
    pdu.address = buffer[index++] << 8;
    pdu.address += buffer[index++];
    pdu.number = buffer[index++] << 8;
    pdu.number += buffer[index++];
    pdu.bytes = buffer[index++];
  } else if(pdu.cmd == MODBUS_CMD_WRT) {  //write read test
    pdu.bytes = buffer[index++];
  } else { //read
    pdu.address = buffer[index++] << 8;
    pdu.address += buffer[index++];
    pdu.number = buffer[index++] << 8;
    pdu.number += buffer[index++];
    pdu.bytes = 0;
  }
  //copy data
  pdu.data = buffer + index;
  return MDET_OK;
}



/************************************************
 *          ModbusTCP
 ************************************************/
int ModbusTCP::packet(uint8_t **ptr)
{
  buffer0[0] = mbap.head >> 8;
  buffer0[1] = mbap.head;
  buffer0[2] = mbap.type >> 8;
  buffer0[3] = mbap.type;
  buffer0[4] = mbap.length >> 8;
  buffer0[5] = mbap.length;
  int index = 6;
  buffer0[index++] = pdu.id;
  buffer0[index++] = pdu.cmd;
  if(packet_mask & 0x01) {
    buffer0[index++] = pdu.address >> 8;
    buffer0[index++] = pdu.address;
  }
  if(packet_mask & 0x02) {
    buffer0[index++] = pdu.number >> 8;
    buffer0[index++] = pdu.number;
  }
  if(packet_mask & 0x04) {
    buffer0[index++] = pdu.bytes;
  }
  
  index += data_length;
  *ptr = buffer0;
  
  return index;
}
/*
*/
void ModbusTCP::build_start(uint8_t id, uint8_t cmd, uint16_t address, uint16_t number, uint8_t bytes)
{
  pdu.id = id;
  pdu.cmd = cmd;
  pdu.address = address;
  pdu.number = number;
  pdu.bytes = bytes;
  pdu.data = buffer0 + 13;
  data_length = 0;
  mbap.length = 7;
  packet_mask = 0x07;
}
/*
*/
void ModbusTCP::build_start(uint8_t id, uint8_t cmd, uint16_t address, uint16_t number)
{
  build_start(id, cmd, address, number, number*2);
  pdu.data = buffer0 + 12;
  mbap.length = 6;
  packet_mask = 0x03;
}
/*
*/
void ModbusTCP::build_start(uint8_t id, uint8_t cmd, uint16_t address)
{
  build_start(id, cmd, address, 1, 2);
  pdu.data = buffer0 + 10;
  mbap.length = 4;
  packet_mask = 0x01;
}
/*
*/
void ModbusTCP::build_start(uint8_t id, uint8_t cmd, uint8_t bytes)
{
  build_start(id, cmd, pdu.address, pdu.number, bytes);
  pdu.data = buffer0 + 9;
  mbap.length = 3;
  packet_mask = 0x04;
}
/*
*/
void ModbusTCP::build_start(uint8_t id, uint8_t cmd)
{
  pdu.id = id;
  pdu.cmd = cmd;
  data_length = 0;
  mbap.length = 2;
  packet_mask = 0;
}
/*
 */
void ModbusTCP::build_end()
{
  mbap.length += data_length;
}
/*
 */
mdet_t ModbusTCP::master_parse(uint8_t *buffer, int len)
{
  if (len < 8){
    return MDET_BADFRAME;
  }
  
  //head check
  uint16_t head = (buffer[0] << 8) + buffer[1];
  if(head != mbap.head) {
    return MDET_BADACK;
  }
  //type check
  uint16_t type = (buffer[2] << 8) + buffer[3];
  if(type != mbap.type) {
    return MDET_BADACK;
  }
  mbap.length = (buffer[4] << 8) + buffer[5];
  
  return ModbusBase::master_parse(buffer + 6, len - 6, false);
}
/*
 */
mdet_t ModbusTCP::slave_parse(uint8_t *buffer, int len)
{
  if (len < 8){
    return MDET_BADFRAME;
  }
  
  mbap.head = (buffer[0] << 8) + buffer[1];
  mbap.type = (buffer[2] << 8) + buffer[3];
  mbap.length = (buffer[4] << 8) + buffer[5];
  
  return ModbusBase::slave_parse(buffer + 6, len - 6, false);
}

